package com.zju.DoctorGo.controller;

import com.zju.DoctorGo.entity.Prescription;
import com.zju.DoctorGo.entity.Result;
import com.zju.DoctorGo.service.PrescriptionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

@CrossOrigin
@RestController
@Slf4j
@RequestMapping("/api/prescriptions")
public class PrescriptionController {

    @Autowired
    private PrescriptionService prescriptionService;

    @PostMapping
    public Result createPrescription(@RequestBody Prescription prescription) {
        log.info("Creating prescription: {}", prescription);
        try {
            prescriptionService.createPrescription(prescription);
            return Result.success();
        } catch (DuplicateKeyException e) {
            log.error("Failed to create prescription due to duplicate key: {}", e.getMessage());
            return Result.error("A prescription with the same ID already exists. Please use a unique ID.");
        } catch (Exception e) {
            log.error("Failed to create prescription: {}", e.getMessage());
            return Result.error("An unexpected error occurred while creating the prescription.");
        }
    }

    @GetMapping("/{id}")
    public Result getPrescription(@PathVariable Long id) {
        log.info("Fetching prescription with ID: {}", id);
        try {
            List<Prescription> prescription = prescriptionService.getPrescription(id);
            if (prescription != null) {
                return Result.success(prescription);
            } else {
                return Result.error("Prescription not found.");
            }
        } catch (Exception e) {
            log.error("Failed to fetch prescription: {}", e.getMessage());
            return Result.error("An error occurred while fetching prescription.");
        }
    }

    @DeleteMapping("/{id}")
    public Result deletePrescription(@PathVariable Long id) {
        log.info("Deleting prescription with ID: {}", id);
        try {
            prescriptionService.deletePrescription(id);
            return Result.success();
        } catch (Exception e) {
            log.error("Failed to delete prescription: {}", e.getMessage());
            return Result.error("An error occurred while deleting prescription.");
        }
    }

    @GetMapping
    public Result getAllPrescriptions() {
        log.info("Fetching all prescriptions");
        try {
            List<Prescription> prescriptions = prescriptionService.getAllPrescriptions();
            return Result.success(prescriptions);
        } catch (Exception e) {
            log.error("Failed to fetch prescriptions: {}", e.getMessage());
            return Result.error("An error occurred while fetching prescriptions.");
        }
    }

    @GetMapping("/{id}/totalPrice")
    public Result getTotalPrice(@PathVariable Long id) {
        log.info("Fetching total price for prescription with ID: {}", id);
        try {
            double totalPrice = prescriptionService.getTotalPrice(id);
            return Result.success(totalPrice);
        } catch (Exception e) {
            log.error("Failed to fetch total price: {}", e.getMessage());
            return Result.error("An error occurred while fetching total price.");
        }
    }

    @PutMapping("/{prescriptionId}/medicine/{medicineId}")
    public Result updatePrescriptionItem(
            @PathVariable Long prescriptionId,
            @PathVariable Long medicineId,
            @RequestParam int quantity) {
        try {
            prescriptionService.updatePrescriptionItem(prescriptionId, medicineId, quantity);
            return Result.success();
        } catch (Exception e) {
            log.error("Failed to update prescription item with prescription ID {} and medicine ID {}: {}", prescriptionId, medicineId, e.getMessage());
            return Result.error("An error occurred while updating prescription item.");
        }
    }

    @DeleteMapping("/{prescriptionId}/medicine/{medicineId}")
    public Result deletePrescriptionItem(
            @PathVariable Long prescriptionId,
            @PathVariable Long medicineId) {
        try {
            prescriptionService.deletePrescriptionItem(prescriptionId, medicineId);
            return Result.success();
        } catch (Exception e) {
            log.error("Failed to delete prescription item with prescription ID {} and medicine ID {}: {}", prescriptionId, medicineId, e.getMessage());
            return Result.error("An error occurred while deleting prescription item.");
        }
    }

    @PostMapping("/{prescriptionId}/medicine/{medicineId}")
    public Result addPrescriptionItem(
            @PathVariable Long prescriptionId,
            @PathVariable Long medicineId,
            @RequestParam int quantity) {
        try {
            prescriptionService.addPrescriptionItem(prescriptionId, medicineId, quantity);
            return Result.success();
        } catch (Exception e) {
            log.error("Failed to add prescription item with prescription ID {} and medicine ID {}: {}", prescriptionId, medicineId, e.getMessage());
            return Result.error("An error occurred while adding prescription item.");
        }
    }
}
